//
//  HttpEngine.m
//  ChinaBookingPhone
//
//  Created by 杨 锐 on 14-7-2.
//  Copyright (c) 2014年 ChinaBooking. All rights reserved.
//

#import "HttpHelper.h"

@implementation HttpHelper

/**
 *  http Post请求
 *  @param url        请求地址
 *  @param parameters 请求参数
 *  @param success    成功回调
 *  @param failure    失败回调
 */
+(void)HttpPostRequest:(NSString *)url
            parameters:(NSDictionary *)parameters
               success:(void (^)(id responseDic))success
               failure:(void (^)(NSError *error))failure{
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer]requestWithMethod:@"POST" URLString:url parameters:parameters error:nil];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject){
        //将返回数据转为字符串
        NSString *jsonStr=[[NSString alloc]initWithData:(NSData*)responseObject encoding:NSUTF8StringEncoding];
        //将字符串转为NSData
        NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
        NSError *error = nil;
        //将NSData转为NSDictionary
        id result = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
        //block回调
        success(result);
    }
    failure:^(AFHTTPRequestOperation *operation, NSError *error){
        failure(error);
    }];
    [operation start];
}

/**
 *  http Get请求
 *  @param url        请求地址
 *  @param parameters 请求参数
 *  @param success    成功回调
 *  @param failure    失败回调
 */
+(void)HttpGetRequest:(NSString *)url
           parameters:(NSDictionary *)parameters
              success:(void (^)(id responseDic))success
              failure:(void (^)(NSError *error))failure{
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer]requestWithMethod:@"Get" URLString:url parameters:parameters error:nil];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject){
        //将返回数据转为字符串
        NSString *jsonStr=[[NSString alloc]initWithData:(NSData*)responseObject encoding:NSUTF8StringEncoding];
        //将字符串转为NSData
        NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
        NSError *error = nil;
        //将NSData转为NSDictionary
        id result = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
        //block回调
        success(result);
    }
    failure:^(AFHTTPRequestOperation *operation, NSError *error){
         failure(error);
    }];
    [operation start];
}

/**
 *  调用webservice
 *  @param url        请求地址
 *  @param parameters 请求参数
 *  @param success    成功回调
 *  @param failure    失败回调
 */
+(void)HttpRequestWebservice:(NSString *)url
                  parameters:(NSDictionary *)parameters
                     success:(void (^)(id responseDic))success
                     failure:(void (^)(NSError *error))failure{
    
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer]requestWithMethod:@"POST" URLString:url parameters:parameters error:nil];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject){
        success(responseObject);
    }
    failure:^(AFHTTPRequestOperation *operation, NSError *error){
         failure(error);
     }];
    [operation start];
}

/**
 *  图片上传
 *
 *  @param url                  上传地址
 *  @param params               参数
 *  @param image                图片Data
 *  @param completionHandler    完成回调块
 *  @param ImgCompressionQuality图片压缩比率，0~1float值代表0%~100%
 *  @param ProgressBlock        图片上传中实时监控进度 参数:float类型从0~1代表0%~100%
 *  @param success              图片上传成功后回调 参数:服务器完成上传后的返回结果
 *  @param failure              图片上传失败回调 参数:上传出现失败时出现的错误对象
 注意:如若在上传图片时不需做任何处理也不需要任何服务器反馈，同事也不需要检测上传时出现的网络错误，可以将ProgressBlock、success、failure皆赋值为空
 *
 *  @return 返回当前上传图片时所使用的的AFHTTPRequestOperation对象;
 */
+(AFHTTPRequestOperation *)HttpPostImgWithURL:(NSString *)url
                                       params:(NSDictionary*)params
                                    ImageData:(UIImage *)image
                        ImgCompressionQuality:(CGFloat)compressionQuality
                          UpLoadProgressBlock:(void (^)(float Progress))ProgressBlock
                            UpLoadWithSuccess:(void (^)(AFHTTPRequestOperation *result))success
                            UpLoadWithFailure:(void (^)(NSError *error))failure
{
    //通过图片对象创建传输的NSData数据
    NSData *imgData=UIImageJPEGRepresentation(image, compressionQuality);
    //使用图片对象、地址、参数创建请求Result
    NSMutableURLRequest *req= [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST"URLString:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData){
        [formData appendPartWithFileData:imgData name:@"image1" fileName:@"image1.jpg" mimeType:@"image/jpeg"];}
                                                                                             error:nil];
    
    //创建请求operation
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:req];
    //开启请求
    [operation start];
    
    //声明成功回调处理块
    void (^successBlock)(AFHTTPRequestOperation *operation, id responseObject);
    //声明失败回调处理块
    void (^failureBlock)(AFHTTPRequestOperation *operation, NSError *error);
    //声明上传进度跟踪块
    void (^UploadBlock)(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite);
    
    //创建成功回调处理块
    successBlock = ^(AFHTTPRequestOperation *operation, id responseObject){
        //不为空则调用成功回调
        if (success != nil){
            success(operation);
        }
    };
    
    //创建失败回调处理块
    failureBlock = ^(AFHTTPRequestOperation *operation, NSError *error){
        //不为空则调用失败回调
        if (failure != nil){
            failure(error);
        }
    };
    
    //创建上传进度跟踪块
    UploadBlock = ^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite){
        //取得文件大小以及发送大小
        CGFloat nowSize   = totalBytesWritten;
        CGFloat countSize = totalBytesExpectedToWrite;
        //计算百分比
        float progress = nowSize/countSize;
        //不为空则调用进度跟踪块
        if (ProgressBlock != nil){
            ProgressBlock(progress);
        }
    };
    
    //设置进度跟踪块
    [operation setUploadProgressBlock:UploadBlock];
    
    //设置图片上传成功回调块及失败回调块
    [operation setCompletionBlockWithSuccess:successBlock failure:failureBlock];
    
    return operation;
}

@end
